import pygame
from src.elements.bullet import Bullet

class PlayerTank(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.level = 1
        self.hp = 1
        self.speed = 2
        self.bullet_speed = 5  # 确保子弹速度与敌人一致
        self.max_bullets = 1
        self.image = pygame.image.load("images/tank_L1_1.png")
        self.rect = self.image.get_rect(center=pos)
        self.direction = "up"
        self.bullets = pygame.sprite.Group()
        self.cooldown = 500  # 毫秒
        self.last_shot = pygame.time.get_ticks()
        self.extra_lives = 0  # 新增备用坦克数量

    def update(self, keys_pressed, game_map):
        new_rect = self.rect.copy()
        if keys_pressed[pygame.K_LEFT]:
            new_rect.x -= self.speed
            self.direction = "left"
        elif keys_pressed[pygame.K_RIGHT]:
            new_rect.x += self.speed
            self.direction = "right"
        elif keys_pressed[pygame.K_UP]:
            new_rect.y -= self.speed
            self.direction = "up"
        elif keys_pressed[pygame.K_DOWN]:
            new_rect.y += self.speed
            self.direction = "down"

        if not game_map.check_collision(new_rect):
            self.rect = new_rect

    def shoot(self):
        now = pygame.time.get_ticks()
        if len(self.bullets) < self.max_bullets and now - self.last_shot >= self.cooldown:
            bullet = Bullet(self.rect.centerx, self.rect.centery, self.direction, self.bullet_speed, "player")
            self.bullets.add(bullet)
            self.last_shot = now
            print("Bullet fired!")  # 添加调试信息

    def upgrade(self, kind):
        if kind == 'star':
            if self.level < 3:
                self.level += 1
                self.hp = self.level
                self.image = pygame.image.load(f"images/tank_L{self.level}_1.png")
        elif kind == 'gun':
            self.bullet_speed += 1
        elif kind == 'shell':
            self.max_bullets = 2
        elif kind == 'tank':
            self.extra_lives += 1  # 增加备用坦克数量
            return 'extra_life'
        return None

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        self.bullets = pygame.sprite.Group([bullet for bullet in self.bullets if bullet.active])
        self.bullets.draw(screen)